package com.sunday.pinxinghui.model.mine;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.TimeCount;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.pinxinghui.MainActivity;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.base.BaseApplication;
import com.sunday.pinxinghui.base.Constant;
import com.sunday.pinxinghui.entity.Member;
import com.sunday.pinxinghui.model.WebViewActivity;
import com.sunday.pinxinghui.network.ApiClient;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.text.InputType.TYPE_CLASS_NUMBER;
import static android.text.InputType.TYPE_CLASS_TEXT;

/**
 * Created by 刘涛 on 2017/8/27.
 */

public class SetPayPwdActivity extends BaseActivity {

    @Bind(R.id.left_btn)
    ImageView leftBtn;
    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.rightTxt)
    TextView rightTxt;
    @Bind(R.id.right_btn)
    ImageView rightBtn;
    @Bind(R.id.common_header)
    RelativeLayout commonHeader;
    @Bind(R.id.et_phone)
    ClearEditText etPhone;
    @Bind(R.id.et_code)
    ClearEditText etCode;
    @Bind(R.id.send_code)
    TextView sendCode;
    @Bind(R.id.et_pwd)
    ClearEditText etPwd;
    @Bind(R.id.btn_save)
    TextView btnSave;
    @Bind(R.id.ll_bind_info)
    LinearLayout llBindInfo;
    @Bind(R.id.txt_pwd)
    TextView txtPwd;

    private TimeCount timeCount;
    private Long memberId;
    private int updateType;
    private Member member;
    private boolean fromPay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_pay_pwd);
        ButterKnife.bind(this);
        llBindInfo.setVisibility(View.GONE);
        updateType = getIntent().getIntExtra("updateType", 1);
        titleView.setText(updateType == 2 ? "设置支付密码" : "设置登录密码");
        etPwd.setHint(updateType == 2 ? "请设置6位数字支付密码" : "请设置登录密码");
        etPwd.setInputType(updateType==2?TYPE_CLASS_NUMBER:TYPE_CLASS_TEXT);
        txtPwd.setText("设置密码");
        fromPay = getIntent().getBooleanExtra("fromPay", false);
        if (updateType != 3) {
            member = BaseApplication.getInstance().getMember();
            etPhone.setText(member != null ? member.getMobile() : "");
            etPhone.setEnabled(false);
            etPhone.setFocusable(false);
        }
        memberId = updateType == 3 ? null : BaseApplication.getInstance().getMember().getId();
        timeCount = new TimeCount(60000, 1000, sendCode);
    }


    @OnClick({R.id.send_code, R.id.btn_save})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_code:
                String mobile = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile) || !StringUtils.isMobileNO(mobile)) {
                    ToastUtils.showToast(mContext, "请输入正确的手机号");
                    return;
                }
                sendCode(mobile);
                break;
            case R.id.btn_save:
                String mobile1 = etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile1) || !StringUtils.isMobileNO(mobile1)) {
                    ToastUtils.showToast(mContext, "请输入正确的手机号");
                    return;
                }
                String code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showToast(mContext, "请输入验证码");
                    return;
                }
                String pwd = etPwd.getText().toString().trim();
                if (TextUtils.isEmpty(pwd)) {
                    ToastUtils.showToast(mContext, "请输入密码");
                    return;
                }

                if (updateType == 2) {
                    if (pwd.length() != 6) {
                        ToastUtils.showToast(mContext, "请输入6位支付密码");
                        return;
                    }
                } else {
                    if (pwd.length() < 6 || pwd.length() > 10) {
                        ToastUtils.showToast(mContext, "请输入6-10位的登录密码");
                        return;
                    }
                }


                showLoadingDialog(0);


                if (updateType == 1) {
                    Call<ResultDO> call = ApiClient.getApiAdapter().updatePassword(memberId, code, MD5Utils.MD5(pwd));
                    call.enqueue(new Callback<ResultDO>() {
                        @Override
                        public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                            if (isFinish || response.body() == null) {
                                return;
                            }
                            dissMissDialog();
                            ResultDO resultDO = response.body();
                            if (response.body().getCode() == 0) {
                                ToastUtils.showToast(mContext, "修改成功！");
                                finish();
                            } else {
                                ToastUtils.showToast(mContext, resultDO.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultDO> call, Throwable t) {
                            dissMissDialog();
                            ToastUtils.showToast(mContext, R.string.network_error);
                        }
                    });
                } else if (updateType == 2) {
                    Call<ResultDO<Member>> call1 = ApiClient.getApiAdapter().updatePayPassword(memberId, code, MD5Utils.MD5(pwd));
                    call1.enqueue(new Callback<ResultDO<Member>>() {
                        @Override
                        public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                            if (isFinish || response.body() == null) {
                                return;
                            }
                            dissMissDialog();
                            ResultDO<Member> resultDO = response.body();
                            if (response.body().getCode() == 0) {
                                ToastUtils.showToast(mContext, "修改成功！");
                                if (resultDO.getResult() != null) {
                                    SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                                    BaseApplication.getInstance().setMember(resultDO.getResult());
                                }
                                if (fromPay) {
                                    Intent data = new Intent();
                                    setResult(RESULT_OK, data);
                                }
                                finish();
                            } else {
                                ToastUtils.showToast(mContext, resultDO.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                            dissMissDialog();
                            ToastUtils.showToast(mContext, R.string.network_error);
                        }
                    });
                } else {
                    forgetPwd(mobile1, code, pwd);
                }
                break;
        }
    }

    private void forgetPwd(String mobile1, String code, String pwd) {
        Call<ResultDO> call = ApiClient.getApiAdapter().forgetPassword(mobile1, code, MD5Utils.MD5(pwd));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                ResultDO resultDO = response.body();
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "修改成功！");
                    finish();
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void sendCode(String mobile) {
        Call<ResultDO> call = ApiClient.getApiAdapter().sendCode(null, mobile, updateType == 2 ? Constant.CODE_FOUR : Constant.CODE_THREE);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    ToastUtils.showToast(mContext, "验证码已发送到手机");
                    timeCount.start();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timeCount != null) {
            timeCount.cancel();
        }
    }
}
